package vn.com.vtv.weather;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.openweathermap.model.DaysInfo;
import org.openweathermap.service.MakeUrl;
import org.openweathermap.service.WeatherRequest;

import vn.com.hoasua.database.smng.LinkMng;
import vn.com.hoasua.database.sobject.LinkPost;
import vn.com.vtv.weather.NetworkAdapter.NetworkResponse;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.widget.RemoteViewsService;

public class WidgetService extends RemoteViewsService {
	/*
	 * So pretty simple just defining the Adapter of the listview here Adapter
	 * is ListProvider
	 */
	static ListProvider adapter;
	Handler hanlder;
	public WidgetService() {
		// TODO Auto-generated constructor stub
		
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		hanlder = new Handler();
	}
	@Override
	public RemoteViewsFactory onGetViewFactory(Intent intent) {
		final NetworkAdapter net = new NetworkAdapter(this);
		Log.e("vtv.weather", "UPDATE_WIDGET");
		int cityId = VTVApplication.prefs.getInt(VTVApplication.KEY_CITY_ID, VTVApplication.KEY_CITY_ID_DEF);
		WeatherRequest request = new MakeUrl(getApplicationContext()).get7DaysById(cityId);
		net.sendHttpGet(request.url, request.params, new NetworkResponse() {

			@Override
			public void onSuccess(String url, ArrayList<NameValuePair> param,
					String json) {
				boolean needUpdate= false;
				LinkMng linkMng = new LinkMng(getApplicationContext());
//				Log.e("json", url+param.toString()+"-"+json);
				ArrayList<LinkPost> links = linkMng.select(LinkMng.link, net.makeGetUrl(url, param));
				if(links==null || links.isEmpty()){
					LinkPost link= new LinkPost(-1, new String[LinkPost.NUM_FIELDS]);
					link.time=System.currentTimeMillis();
					link.link=net.makeGetUrl(url, param);
					link.xml=json;
					linkMng.insertNewTo(link.getValues());
					needUpdate=true;
				}else{
					LinkPost link = links.get(0);
					if(json.length()>20 && !json.contains("error") && link.xml.equals(json)){
						needUpdate=false;
					}else{
						needUpdate=true;
						link.time=System.currentTimeMillis();
						link.xml=json;
						linkMng.edit(link._id, link.getValues());
					}
				}
				if(needUpdate){
					final DaysInfo sevenDays=DaysInfo.parse(json);
					if(sevenDays!=null){
						
						hanlder.post(new Runnable() {
							
							@Override
							public void run() {
								adapter.setDataContext(sevenDays);
								sendBroadcast(new Intent("android.appwidget.action.APPWIDGET_UPDATE"));
							}
						});
					}
				}
			}

			@Override
			public void onFailed(String url, ArrayList<NameValuePair> param,
					String json) {
				sendBroadcast(new Intent("android.appwidget.action.APPWIDGET_UPDATE"));
			}
			
		});
		@SuppressWarnings("unused")
		int appWidgetId = intent.getIntExtra(
				AppWidgetManager.EXTRA_APPWIDGET_ID,
				AppWidgetManager.INVALID_APPWIDGET_ID);
		if(adapter == null){
			adapter = new ListProvider(getApplicationContext());
		}
		LinkMng linkmng = new LinkMng(getApplicationContext());
		ArrayList<LinkPost> link = linkmng.select(LinkMng.link, net.makeGetUrl(request.url, request.params));
		if(link!=null && !link.isEmpty()){
			String json = link.get(0).xml;
			DaysInfo sevenDays=DaysInfo.parse(json);
			adapter.setDataContext(sevenDays);
		}else{
			adapter.setDataContext(intent);
		}
		hanlder.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				sendBroadcast(new Intent(WidgetProvider.SYNC_COMPLETE));
			}
		}, 500);
		
		return adapter;
	}

}
